package com.spider.base;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.spider.exception.ExecuterServiceIsNullException;
import com.spider.util.ExecuteServiceType;

public abstract class BaseTask<T> implements Callable<T> {
	
	private static final Logger log = Logger.getLogger(BaseTask.class);
	
	/** before call */
	public void before(){}
	
	public T call() throws Exception {
		before();
		T t = null;
		try{
			t = process();
		}catch(Exception e){
			log.error("task execute false!");
		}finally{ // what ever after() can executed
			after();
		}
		return t; 
	}
	
	/**after call */
	public void after(){}
	
	/** 执行操作
	 * @return
	 */
	public abstract T process();
	
	/**启动 线程
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 * @throws ExecuterServiceIsNullException */
	public static <T> T startTask(BaseTask<T> task,ExecuteServiceType type) throws InterruptedException, ExecutionException, ExecuterServiceIsNullException{
		T result = null;
		try {
			result =  BaseExecute.ExecuteOne(task,type).get();
		} catch (InterruptedException e) {
			log.error("this current thread is interrupted");
			throw e;
		} catch (ExecutionException e) {
			log.error(" execute exception!");
			throw e;
		}
		return result;
	}
	
	/**启动 线程
	 * @throws InterruptedException 
	 * @throws ExecutionException 
	 * @throws ExecuterServiceIsNullException */
	public static <T> List<T> startTaskCollection(List<BaseTask<T>> tasks,ExecuteServiceType type) throws ExecutionException, InterruptedException, ExecuterServiceIsNullException{
		return startTaskCollection(tasks,type,null,null);
	}
	
	/**启动 线程
	 * @throws InterruptedException 
	 * @throws ExecutionException 
	 * @throws ExecuterServiceIsNullException */
	public static <T> List<T> startTaskCollection(List<BaseTask<T>> tasks,ExecuteServiceType type,Long timeout,TimeUnit unit) throws InterruptedException, ExecutionException, ExecuterServiceIsNullException{
		List<T> result = null;
		List<Future<T>> futures;
		try {
			futures = BaseExecute.ExecuteBitch(tasks,type,timeout,unit);
			if(futures!=null){
				result = new ArrayList<T>();
				for(Future<T> f : futures){
					result.add(f.get());
				}
			}
		} catch (InterruptedException e) {
			log.error("this current thread is interrupted");
			throw e;
		} catch (ExecutionException e) {
			log.error(" execute exception!");
			throw e;
		}
		return result;
	}
	
	/*** 执行定时任务
	 * @param task
	 * @param type
	 * @param timeout
	 * @param unit
	 */
	public static <T> void startTaskByTime(BaseTask<T> task,ExecuteServiceType type,Long timeout,TimeUnit unit){
		
	}
	
}
